package com.abel.classloader;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import java.io.*;

/**
 * @author xiachao
 * @date 2019/1/2
 */
public class CustomClassLoader extends ClassLoader{

    private String root;
    /**
     * root path
     * @param root
     */
    public CustomClassLoader(String root){
        if(StringUtils.isBlank(root)){
            throw new IllegalArgumentException("Root Path can not be empty!");
        }
        if(!new File(root).exists()){
            new FileNotFoundException("Root path is not exist!");
        }
        this.root = root;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] clazz = null;
        try {
            clazz = this.findClassAsStream(name);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (clazz == null) {
            throw new ClassNotFoundException();
        } else {
            return defineClass(name, clazz, 0, clazz.length);
        }
    }

    private byte [] findClassAsStream(String name) throws IOException {
        if(StringUtils.isBlank(name)){
            throw new IllegalArgumentException("Class name can not be empty!");
        }
        String path = this.root + name.replace('.', File.separatorChar) + ".class";
        InputStream inputStream = new FileInputStream(path);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte [] buff = new byte[1024];
        int len;
        while((len = inputStream.read(buff)) > 0){
            outputStream.write(buff, 0, len);
        }
        return outputStream.toByteArray();
    }

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        CustomClassLoader loader = new CustomClassLoader("/Users/heaveneleven/IdeaProjects/headlineback-web/target/headlineback-web/WEB-INF/classes/");
        Class clazz = loader.findClass("com.dianping.headline.back.entity.keep.DailyCounter");
        Object obj = clazz.newInstance();
        System.out.println(JSON.toJSONString(obj));
    }
}
